package com.gpstracker.services;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import com.gpstracker.db.MyDatabase;
import com.gpstracker.overlays.MyItemizedOverlay;

@SuppressWarnings("unused")
public class OverlayHandler {

	private static final String tag = "OVERLAY_ADDER";
	MyItemizedOverlay myItemizedOverlay;
	Context context;

	public OverlayHandler(MyItemizedOverlay myItemizedOverlay, Context context) {

		this.myItemizedOverlay = myItemizedOverlay;
		this.context = context;
	}

	public boolean fill() {
		FillerOverlay fillerOverlay = new FillerOverlay();
		fillerOverlay.execute();
		return true;
	}

	class FillerOverlay extends AsyncTask<String, String, String>{


		@SuppressLint("NewApi")
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.i("FILLER_OVERLAY", "do_in_background");  
			MyDatabase myDatabase = new MyDatabase(context);
			myDatabase.open();
			Cursor cursor = myDatabase.fetchLocations();

			cursor.moveToFirst();
			while (cursor.isAfterLast() == false) 
			{
				Log.i(tag, "lat: "+(int)(cursor.getDouble(2)*1000000)+"  lon: "+(int)(cursor.getDouble(1)*1000000));  
				Double lat=cursor.getDouble(2);
				Double lon=cursor.getDouble(1);

				if(! (lat==0 && lon==0)){

					GeoPoint point= new GeoPoint((int)(cursor.getDouble(2)*1000000), (int)(cursor.getDouble(1)*1000000));
					String title ="Record mumber "+String.valueOf(cursor.getInt(0));
					title += "\nt: "+String.valueOf(cursor.getInt(4));
					String description = "POINT DESCRIPTION";
					for(int i=0; i<cursor.getColumnCount(); i++){


						String column_name= cursor.getColumnName(i);

						if(!column_name.equals("fulltime")){
							description += "\n";
							if (column_name.equals("timezone_offset")){
								description += "timezone offset: "+cursor.getInt(i)/3600000 + " hours";
							}
							else{
								description += column_name+": ";
								int type = cursor.getType(i);
								switch (type) {
								case Cursor.FIELD_TYPE_INTEGER:
									description += cursor.getInt(i);
									break;
								case Cursor.FIELD_TYPE_STRING:
									description += cursor.getString(i);
									break;
								case Cursor.FIELD_TYPE_FLOAT:
									description += cursor.getFloat(i);
									break;
								default:
									break;
								}
							}
						}
					}
					OverlayItem overlayItem = new OverlayItem(point, title, description);
					myItemizedOverlay.addOverlay(overlayItem);
				}
				cursor.moveToNext();

			}


			return null;
		}
	}
}
